<?php

namespace app\shop\controller\api;

use app\ApiController;
use app\shop\model\SlideModel;
use app\shop\model\GoodsModel;
use app\shop\model\NavMenuModel;
use think\Db;
use wangdiantong\Wdtwms;

class Index extends ApiController
{
    public function indes()
    {
        $xml = '<?xml version="1.0" encoding="utf-8"?>
        <request>
          <deliveryOrder>
            <deliveryOrderCode>2021080386994</deliveryOrderCode>
            <deliveryOrderId>CK202108040006</deliveryOrderId>
            <warehouseCode>wms_lt_xpxgWDT</warehouseCode>
            <orderType>JYCK</orderType>
            <orderConfirmTime>2021-08-04 16:46:19</orderConfirmTime>
            <outBizCode>CK202108040006</outBizCode>
          </deliveryOrder>
          <packages>
            <package>
              <logisticsCode>ZTO</logisticsCode>
              <expressCode>7897</expressCode>
              <packageCode>7897</packageCode>
              <weight>11.0000</weight>
              <extendProps>
                <postage>0.0000</postage>
              </extendProps>
              <items>
                <item>
                  <itemCode>161</itemCode>
                  <quantity>10</quantity>
                </item>
              </items>
            </package>
          </packages>
          <orderLines>
            <orderLine>
              <itemCode>161</itemCode>
              <inventoryType>ZP</inventoryType>
              <actualQty>10</actualQty>
              <orderLineNo>1</orderLineNo>
              <remark>
              </remark>
              <batchs>
                <batch>
                  <batchCode>
                  </batchCode>
                  <expireDate>
                  </expireDate>
                  <productDate>
                  </productDate>
                  <productionDate>
                  </productionDate>
                  <actualQty>10</actualQty>
                  <inventoryType>ZP</inventoryType>
                </batch>
              </batchs>
            </orderLine>
          </orderLines>
        </request>

';
        $sd = json_decode(json_encode(simplexml_load_string($xml, 'SimpleXMLElement', LIBXML_NOCDATA)), true);

        $order_sn = $sd['deliveryOrder']['deliveryOrderCode'];//商城订单编号
        $logistics = $sd['packages']['package'];
        $logisticsCode = $logistics['logisticsCode'];//快递编码
        $expressCode = $logistics['expressCode'];//物流单号
        $packageCode = $logistics['packageCode'];//包裹编号
        var_dump();
        die;
    }

    /**
     * 发货回调地址
     */
    public function wdt_notify()
    {
        $post = request()->get();
        $postStr = file_get_contents("php://input");
        $document = $_SERVER['DOCUMENT_ROOT'];
        $wdt = new Wdtwms();
        switch ($post['method']) {
            case 'WDT_WMS_ENTRYORDER_CONFIRM': //入库回调
                $filname = $document . '/log/' . 'log_' . date('Y-m-d') . 'in_wdt.txt';
                file_put_contents($filname, date("Y-m-d H:i:s") . "\r\n" . print_r($post, true) . "\r\n" . $postStr . "\r\n\n\n\n", FILE_APPEND);
                $result = array(
                    'flag' => 'success',
                    'code' => 0,
                    'message' => '成功确认入库单'
                );
                $result = $wdt->arr_to_xml($result);
                break;
            case 'WDT_WMS_STOCKOUT_CONFIRM': //出库单确认接口
                $filname = $document . '/log/' . 'log_' . date('Y-m-d') . 'out_wdt.txt';
                file_put_contents($filname, date("Y-m-d H:i:s") . "\r\n" . print_r($post, true) . "\r\n" . $postStr . "\r\n\n\n\n", FILE_APPEND);
                $result = array(
                    'flag' => 'success',
                    'code' => 0,
                    'message' => 'success'
                );
                $result = $wdt->arr_to_xml($result);
                break;
            case 'WDT_WMS_DELIVERYORDER_CONFIRM'://发货确认接口
               $result = array(
                    'flag' => 'success',
                    'code' => 0,
                    'message' => 'success'
                );
                $result = $wdt->arr_to_xml($result);
                $xml_data=json_decode(json_encode(simplexml_load_string($postStr, 'SimpleXMLElement', LIBXML_NOCDATA)), true);
                $order_sn = $xml_data['deliveryOrder']['deliveryOrderCode'];//商城订单编号
                $logistics = $xml_data['packages']['package'];
                $logisticsCode = $logistics['logisticsCode'];//快递编码
                $expressCode = $logistics['expressCode'];//物流单号
                $packageCode = $logistics['packageCode'];//包裹编号
                $order_type = substr($order_sn, 0, 2);
                $update['invoice_no'] = $expressCode;
                $update['packageCode'] = $packageCode;
                $update['update_time'] = time();
                if ($order_type == 'ws') {
                    $filname = $document . '/log/' . 'log_' . date('Y-m-d') . 'send_wdt_t.txt';
                    file_put_contents($filname, date("Y-m-d H:i:s") . "\r\n" . print_r($post, true) . "\r\n" . $postStr . "\r\n\n\n\n", FILE_APPEND);
                    //提货
                    Db::name('channel_order_info')->where(array('order_sn' => $order_sn))->update($update);
                } else {
                    $filname = $document . '/log/' . 'log_' . date('Y-m-d') . 'send_wdt.txt';
                    file_put_contents($filname, date("Y-m-d H:i:s") . "\r\n" . print_r($post, true) . "\r\n" . $postStr . "\r\n\n\n\n", FILE_APPEND);
                    //更新商城订单运单号码
                    Db::name('shop_order_info')->where(array('order_sn' => $order_sn))->update($update);

                }


                break;

            default:
                $result = "回传地址";
        }
        echo $result;
        die;

    }



    /*------------------------------------------------------ */
    //-- 自定义商城首页
    /*------------------------------------------------------ */
    public function getIndexInfo()
    {
        $ShopPageTheme = new \app\shop\model\ShopPageTheme();
        $data['page'] = $ShopPageTheme->getToWxApp();
        $data['tipsubscribe'] = 0;
        $source = request()->header('source');
        if ($source == 'H5-WX') {
            $openid = input('openid', '', 'trim');
            if (empty($openid) == false) {
                $where[] = ['wx_openid', '=', $openid];
                $where[] = ['is_mp', '=', 0];
                $subscribe = (new \app\weixin\model\WeiXinUsersModel)->where($where)->value('subscribe');
                $data['tipsubscribe'] = $subscribe == 1 ? 0 : 1;
            }
        }
        return $this->success($data);
    }
    /*------------------------------------------------------ */
    //-- 自定义页页
    /*------------------------------------------------------ */
    public function getDiyPage()
    {
        $pageid = input('pageid', 0, 'intval');
        if ($pageid < 1) {
            return $this->error('传参错误.');
        }
        $ShopPageTheme = new \app\shop\model\ShopPageTheme();
        $data['page'] = $ShopPageTheme->getToWxApp($pageid);
        return $this->success($data);
    }

    /**
     *商城订单统计待发货
     */
    public function shopOrder()
    {

        $where[] = ['order_status', '=', 1];
        $where[] = ['is_after_sale', '=', 0];
        $where[] = ['is_status', '=', 1];
        $where[] = ['is_timing', '=', 0];
        $data_info = Db::name('shop_order_info')->where($where)->limit(50)->field('order_id,order_sn,pay_time')->order('order_id desc')->select();

        foreach ($data_info as $k => $v) {
            $day1 = date('Y-m-d', $v['pay_time']);
            $day2 = date('Y-m-d');
            $diff = diffBetweenTwoDays($day1, $day2);
//            echo $diff."\n";
            if ($diff > 3) {
                //发送预警
                $this->admin_msg(array('order_id' => $v['order_id'], 'day_num' => $diff), 1);
            }
            Db::name('shop_order_info')->where(array('order_id' => $v['order_id']))->update(array('not_send_day' => $diff, 'is_timing' => 1));
        }
//
    }

    /**
     *商城订单统计待发货更新状态为0
     */
    public function shopOrderupdate()
    {
        $where[] = ['order_status', '=', 1];
        $where[] = ['is_after_sale', '=', 0];
        $where[] = ['is_status', '=', 1];
        $where[] = ['is_timing', '=', 1];
        $data_info = Db::name('shop_order_info')->where($where)->field('order_id,order_sn,pay_time')->order('order_id desc')->select();
        foreach ($data_info as $k => $v) {
            Db::name('shop_order_info')->where(array('order_id' => $v['order_id']))->update(array('is_timing' => 0));

        }
    }

    /**
     * 后台预警功能-超过3天发送消息
     */
    public function admin_msg($data, $type)
    {
        $where['order_id'] = $data['order_id'];
        $where['status'] = 1;
        $where['type'] = $type;
        $data['type'] = $type;

        $info = Db::name('shop_order_not_shipped')->where($where)->find();
        if ($info) {
            $update['day_num'] = $data['day_num'];
            $update['update_time'] = time();
            Db::name('shop_order_not_shipped')->where($where)->update($update);
        } else {
            $data['add_time'] = time();
            $data['update_time'] = time();

            Db::name('shop_order_not_shipped')->insert($data);
        }

    }

    /**
     * 待提货订单
     */
    public function tihuo()
    {
//        select * from channel_order_info where order_status=1 and shipping_status=0 order by order_id desc
        $data_info = Db::name('channel_order_info')->where(array('order_status' => 1, 'shipping_status' => 0, 'is_status' => 1, 'is_timing' => 0))->limit(50)->field('order_id,add_time')->select();
        foreach ($data_info as $k => $v) {
            $day1 = date('Y-m-d', $v['add_time']);
            $day2 = date('Y-m-d');
            $diff = diffBetweenTwoDays($day1, $day2);
//            echo $diff."\n";
            if ($diff > 3) {
                //发送预警
                $this->admin_msg(array('order_id' => $v['order_id'], 'day_num' => $diff), 2);
            }
            Db::name('channel_order_info')->where(array('order_id' => $v['order_id']))->update(array('not_send_day' => $diff, 'is_timing' => 1));
        }
    }

    /**
     * 待提货订单更新状态为0
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \think\exception\PDOException
     */
    public function tihuoupdate()
    {
        $data_info = Db::name('channel_order_info')->where(array('order_status' => 1, 'shipping_status' => 0, 'is_status' => 1, 'is_timing' => 1))->field('order_id,add_time')->select();
        foreach ($data_info as $k => $v) {
            Db::name('channel_order_info')->where(array('order_id' => $v['order_id']))->update(array('is_timing' => 0));

        }
    }

}
